package com.yanqu.road.server.gameplayer.module.mall;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.apprentice.config.ApprenticeConfig;
import com.yanqu.road.entity.activity.assistantcostumemall.AssistantMallRandomGoods;
import com.yanqu.road.entity.activity.mall.MallActivityInfo;
import com.yanqu.road.entity.activity.oldplayerreturn.OldPlayerReturnShopLimit;
import com.yanqu.road.entity.activity.suitang.config.SuiTangConfigSync;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.config.skin.SkinInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.estatewar.palace.UserPalaceData;
import com.yanqu.road.entity.goods.MallRandomGoods;
import com.yanqu.road.entity.log.LogBuy;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.entity.servercenter.MallRebate;
import com.yanqu.road.entity.task.args.union.UnionActivityTaskArgs;
import com.yanqu.road.logic.bussiness.player.UserMallBuyBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.pb.mall.MallProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityMallModule;
import com.yanqu.road.server.gameplayer.module.activity.oldplayerreturn.OldPlayerReturnModule;
import com.yanqu.road.server.gameplayer.module.activity.suitang.SuiTangModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.*;
import com.yanqu.road.server.gameplayer.module.recharge.RechargeGainModule;
import com.yanqu.road.server.gameplayer.module.task.TaskModule;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.HideMallMgr;
import com.yanqu.road.server.manger.MallRebateMgr;
import com.yanqu.road.server.manger.VipMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.MallActivityMgr;
import com.yanqu.road.server.manger.activity.apprentice.ApprenticeMgr;
import com.yanqu.road.server.manger.activity.assistantcostumemall.AssistantCostumeMallActivityMgr;
import com.yanqu.road.server.manger.activity.oldplayerreturn.OldPlayerReturnMgr;
import com.yanqu.road.server.manger.activity.suitang.SuiTangMgr;
import com.yanqu.road.server.manger.activity.zhenhuan.ZhenHuanMgr;
import com.yanqu.road.server.manger.config.*;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.palace.PalaceActivity;
import com.yanqu.road.server.manger.palace.PalaceActivityMgr;
import com.yanqu.road.server.manger.recharge.RechargeMgr;
import com.yanqu.road.server.pb.MallPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class MallModule extends GeneralModule {

    private Map<Integer, UserMallBuyCount> userMallBuyCountMap;

    private List<MallActivityInfo> mallActivityInfoList = new ArrayList<>();

    public MallModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        for (UserMallBuyCount buyCount : userMallBuyCountMap.values()) {
            if (buyCount.isInsertOption()) {
                UserMallBuyBussiness.addUserMallBuyCount(buyCount);
            } else if (buyCount.isUpdateOption()) {
                UserMallBuyBussiness.updateUserMallBuyCount(buyCount);
            }
        }
        return true;
    }

    @Override
    public boolean loadData() {
        userMallBuyCountMap = UserMallBuyBussiness.getUserMallBuyCountMap(player.getUserId());
        return true;
    }

    @Override
    public void loginSendMsg() {
        if (null != userMallBuyCountMap) {
            syncMallBuyCount(new ArrayList<>(userMallBuyCountMap.values()));
        }
        sendMallActivity(MallActivityMgr.getInTimeActivityList());
    }

    @Override
    public void afterLogin() {
        syncMallRebate();
    }

    public void sendMallActivity(List<MallActivityInfo> activityInfoList) {
        if (null != activityInfoList) {
            player.sendPacket(Protocol.U_MALL_ACTIVITY_LIST, MallPb.parseMallActivityListMsg(activityInfoList, player.getLanguage()));
            mallActivityInfoList = activityInfoList;
        }
    }

    private void syncMallBuyCount(List<UserMallBuyCount> userMallBuyCountList) {
        List<UserMallBuyCount> syncList = new ArrayList<>();
        for (UserMallBuyCount userMallBuyCount : userMallBuyCountList) {
            UserMallBuyCount userMall = player.getModule(ActivityMallModule.class).getUserMall(userMallBuyCount.getMallId());
            if (userMall == null) {//打个补丁,防止重复同步,另外一边的购买记录是一定对的。
                syncList.add(userMallBuyCount);
            }
        }
        player.sendPacket(Protocol.U_MALL_BUY_COUNT_SYNC, MallPb.parseMallBuyCountListMsg(syncList));
    }

    private void syncMallBuyCount(UserMallBuyCount userMallBuyCount) {
        if (null != userMallBuyCount) {
            List<UserMallBuyCount> syncList = new ArrayList<>();
            syncList.add(userMallBuyCount);
            syncMallBuyCount(syncList);
        }
    }

    public ReturnData preBuyGoods(int mallId, int count) {
        if (count < 1 || count > GameConfig.MALL_BUY_MAX_COUNT) {
            return new ReturnData(GameErrorCode.E_MALL_COUNT_NOT_ZERO);
        }
        MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
        if (null == mallInfo) {
            return new ReturnData(GameErrorCode.E_MALL_NO_EXIST);
        }
        int vipLevel = VipMgr.getVipLv(player.getModule(PlayerModule.class).getUserInfo().getVipExp());
        if (vipLevel < mallInfo.getVipLimit()) {
            return new ReturnData(GameErrorCode.E_MALL_LIMIT_BUY_VIP);
        }

        if (mallInfo.getActivityId() > 0){
            if (player.getModule(ActivityMallModule.class).isLimitBuy(mallInfo, count)) {
                return new ReturnData(GameErrorCode.E_MALL_LIMIT_BUY);
            }

            ActivityInfo activityInfo = ActivityMgr.getOpenActivityInfo(mallInfo.getActivityId());
            if (activityInfo != null && activityInfo.getType() > eActivityType.SuiTang.getValue()) {//隋唐之后的活动,商店购买只能用S_CROSS_ACTIVITY_BUY_GOODS
                return new ReturnData(GameErrorCode.E_MALL_LIMIT_BUY);
            }
            if (activityInfo != null && activityInfo.getType() == eActivityType.SuiTang.getValue()) {
                boolean stageBeginTimeLimit = true;
                SuiTangConfigSync config = SuiTangMgr.getConfig();
                if (config != null) {
                    try {
                        long stage1BeginTime = config.getStage1TimeList().get(0).get(0);
                        long zeroTimeStamp = DateHelper.getZeroTimeStamp(stage1BeginTime) + 10 * DateHelper.MINUTE_MILLIONS;
                        if (System.currentTimeMillis() >= zeroTimeStamp && player.getModule(SuiTangModule.class).hasCamp()) {
                            stageBeginTimeLimit = false;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (stageBeginTimeLimit) {
                    return new ReturnData(GameErrorCode.E_ACTIVITY_PREPARE_CAN_NOT_BUY);
                }
            }
            if(mallInfo.getMallMarkId() > 0 && HideMallMgr.markIdIsShield(mallInfo.getMallMarkId())){
                return new ReturnData(GameErrorCode.E_MALL_MARK_ID_SHIELD);
            }
        }

        //系统解锁限制
        if (mallInfo.getSystemLimit().size() > 0) {
            for (Integer systemId : mallInfo.getSystemLimit()) {
                if (!SystemOpenMgr.systemOpen(player, systemId)) {
                    return new ReturnData(GameErrorCode.E_SYSTEM_NO_OPEN);
                }
            }
        }

        if (mallInfo.getShopType() == eShopType.GoodsBagMall.getValue() && count > 1) {
            if (vipLevel < GameConfig.GIFT_QUICK_BUY_VIP_LIMIT) {
                return new ReturnData(GameErrorCode.E_MALL_LIMIT_BUY_VIP);
            }
        }

        if (mallInfo.getCategory() != eMallCategory.NormalProp.getValue()) {
            return new ReturnData(GameErrorCode.E_MALL_NO_EXIST);
        }

        if (mallInfo.getShopType() == eShopType.BeautySkinMall.getValue() || mallInfo.getShopType() == eShopType.PatronsSkinMall.getValue()) {
            MallRandomGoods mallRandomGoods = MallMgr.getMallRandomGoodsByShopType(mallInfo.getShopType());
            if (mallRandomGoods == null) {
                return new ReturnData(GameErrorCode.E_MALL_NO_EXIST);
            }
            if (!mallRandomGoods.getMallIdList().contains(mallId)) {
                return new ReturnData(GameErrorCode.E_MALL_GOODS_IS_OVER_TIME);
            }
        }

        if (mallInfo.getShopType() == eShopType.AssistantSkinMall.getValue()) {
            AssistantMallRandomGoods mallRandomGoods = AssistantCostumeMallActivityMgr.getMallRandomGoods();
            if (mallRandomGoods == null) {
                return new ReturnData(GameErrorCode.E_MALL_NO_EXIST);
            }
            if (!mallRandomGoods.getMallIdList().contains(mallId)) {
                return new ReturnData(GameErrorCode.E_MALL_GOODS_IS_OVER_TIME);
            }
            resetAssistantSkinMall(mallRandomGoods);
        }


        if (mallInfo.getShopType() == eShopType.SecretVolumeMall.getValue()) {
            UserSecretVolume userSecretVolume = player.getModule(SecretVolumeModule.class).getUserSecretVolume();
            //获取mall param
            long mallParam = MallRechargeConfigMgr.getParamValue(mallInfo);
            if (userSecretVolume == null || userSecretVolume.getNo() != mallParam) {
                return new ReturnData(GameErrorCode.E_MALL_BUY_SECRET_VOLUME_NO_ERROR);
            }
        }

        if (mallInfo.getShopType() == eShopType.CaiShenMall87.getValue()) {
            Property property = PropertyHelper.parseStringToProperty(mallInfo.getReward());
            for (Integer goodsId : property.getGoods().keySet()) {
                GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
                if (goodsInfo == null) {
                    return new ReturnData(GameErrorCode.E_MALL_NO_EXIST);
                }
                UserBeauty userBeauty = player.getModule(BeautyModule.class).getUserBeauty(Integer.parseInt(goodsInfo.getExtendParam()));
                if (userBeauty == null) {
                    return new ReturnData(GameErrorCode.E_MALL_CAI_SHEN_NO_BEAUTY);
                }
            }
        }

        if (mallInfo.getShopType() == eShopType.CaiShenMall88.getValue()) {
            Property property = PropertyHelper.parseStringToProperty(mallInfo.getReward());
            for (Integer goodsId : property.getGoods().keySet()) {
                SkinInfo skinInfo = SkinMgr.getSkinInfo(goodsId);
                if (skinInfo == null) {
                    return new ReturnData(GameErrorCode.E_SKIN_NOT_EXIST);
                }
                UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(skinInfo.getBelongRole());
                if (userPatrons == null) {
                    return new ReturnData(GameErrorCode.E_MALL_CAI_SHEN_NO_PATRONS);
                }
            }
        }


        //门客组合不再受活动限制
        //是否门客组合活动限制商品
//		if(MallMgr.isPatronsCombActivityLimit(mallInfo)){
//			ret = GameErrorCode.E_MALL_PATRONS_COMB_ACTIVITY_LIMIT;
//			return;
//		}

        //是否珍兽组合活动限制商品
        if (MallMgr.isVehicleCombActivityLimit(mallInfo)) {
            //  return new ReturnData(GameErrorCode.E_MALL_VEHILCE_COMB_ACTIVITY_LIMIT);
        }

        if (mallInfo.getActivityId() > 0) {
            if (!MallActivityMgr.activityInTime(mallInfo.getActivityId())) {//过期
                return new ReturnData(GameErrorCode.E_MALL_NO_EXIST);
            }
        }

        //七日活动限购
        if (ConfigMgr.isSevenDayLimitMall(mallId)) {
            int days = ConfigMgr.getSevenDayActiveIndex(mallId) + 1;
            int offsetDays = player.getModule(TaskModule.class).getSevenDayOffsetDays();
            if (offsetDays > 8) {
                return new ReturnData(GameErrorCode.E_MALL_BUY_SEVEN_DAY_OVER_TIME);
            }
            if (days > offsetDays) {
                return new ReturnData(GameErrorCode.E_MALL_BUY_SEVEN_DAY_NO_IN_TIME);
            }
        }

        //商会限购
        if (MallMgr.isUnionLimit(player, mallInfo)) {
            return new ReturnData(GameErrorCode.E_MALL_BUY_UNION_LEVEL_NO_ENOUGH);
        }

        if (player.getModule(MallModule.class).isLimitBuy(mallInfo.getMallId(), count)) {
            return new ReturnData(GameErrorCode.E_MALL_LIMIT_BUY);
        }

        // 转盘兑换商店限购
        if (mallInfo.getShopType() == eShopType.TurntablePatronsMall.getValue() || mallInfo.getShopType() == eShopType.TurntableBeautyMall.getValue()) {
            List<String> limitMallList = StringUtils.stringToStringList(GameConfig.TURNTABLE_MALL_REGISTER_TIME_LIMIT, "\\|");
            for (String limitMall : limitMallList) {
                List<Integer> limitMallParam = StringUtils.stringToIntegerList(limitMall, ",");
                int limitMallId = limitMallParam.get(0);
                int limitTime = limitMallParam.get(1);
                if (limitMallId == mallId) {
                    // 时间限制
                    long canBuyTime = DateHelper.getZeroTimeStamp(player.getUserInfo().getRegisterTime() * 1000) + limitTime * 86400000;
                    if (DateHelper.getTodayZeroTimeStamp() < canBuyTime) {
                        return new ReturnData(GameErrorCode.E_BUY_MALL_REGISTER_TIME_NO_ENOUGH);
                    }
                    // 不能重复获得限制
                    for (Map.Entry<Integer, BigInteger> entry : mallInfo.getRewardProp().getGoods().entrySet()) {
                        if (player.getModule(PatronsModule.class).getUserPatrons(entry.getKey()) != null) {
                            return new ReturnData(GameErrorCode.E_PATRONS_CAN_NOT_REPEATED_GET);

                        }
                        if (player.getModule(BeautyModule.class).getUserBeauty(entry.getKey()) != null) {
                            return new ReturnData(GameErrorCode.E_BEAUTY_ALREADY_EXIST);
                        }
                    }
                    break;
                }
            }
        }

        //财神密卷第三期开始，兑换商店新增鲁班，只有购买了当期的财神密卷才可以兑换鲁班
        if (mallInfo.getShopType() == eShopType.SecretVolumeMall.getValue()) {
            Property reward = PropertyHelper.parseStringToProperty(mallInfo.getReward());
            if (reward.getCountByGoodsId(GameConfig.PATRON_102432_ID).compareTo(BigInteger.ZERO) > 0) {
                //商品期数
                //获取mall param
                int no = (int) MallRechargeConfigMgr.getParamValue(mallInfo);
                if (no < 3) {
                    return new ReturnData(GameErrorCode.E_PATRONS_NO_FOUND);

                }
                UserSecretVolume userSecretVolume = player.getModule(SecretVolumeModule.class).getUserSecretVolume();
                if (userSecretVolume.getNo() != no || !userSecretVolume.isBuy()) {
                    return new ReturnData(GameErrorCode.E_PATRONS_SECRET_VOLUME_MALL_EXCHANGE);
                }
                //已经兑换过这个门客了
                UserPatrons patron102432 = player.getModule(PatronsModule.class).getUserPatrons(GameConfig.PATRON_102432_ID);
                if (patron102432 != null) {
                    return new ReturnData(GameErrorCode.E_PATRONS_NO_FOUND);
                }
            }
        }

        if(mallInfo.getShopType() == eShopType.PalaceExchangeMall.getValue()){//皇宫兑换商店有限制条件
            PalaceActivity palaceActivity = PalaceActivityMgr.getInTimePalaceActivity();
            if(null == palaceActivity){
                return new ReturnData(GameErrorCode.E_PALACE_ACTIVITY_NO_FOUND);
            }
            int palacePos = 0;
            UserPalaceData userPalaceData = palaceActivity.getUserPalaceData(player.getUserId());
            if(null != userPalaceData){
                palacePos = userPalaceData.getPos();
            }
            int titleType = palaceActivity.getTitleType(palacePos);
            if(MallMgr.isPalaceMallLimit(titleType, mallInfo)){
                return new ReturnData(GameErrorCode.E_PALACE_TITLE_TYPE_NO_ENOUGH);
            }
        }

        if (mallInfo.getShopType() == eShopType.ZhenHuanSecondProcessIngotsShop.getValue() || mallInfo.getShopType() == eShopType.ZhenHuanThirdProcessIngotsShop.getValue()) {
            //二 三阶段元宝礼包需要有资格才能买
            if (!ZhenHuanMgr.isActivityAble(player.getUserId(), mallInfo.getActivityId())) {
                return new ReturnData(GameErrorCode.E_ZHENHUAN_THIRD_PROCESS_USER_NOT_FOUND);
            }
        }

        //爱徒门客商店，爱徒活动进行期间不能购买
        if (mallInfo.getShopType() == eShopType.ApprenticePatronsMall.getValue()) {
            for (ApprenticeConfig apprenticeConfig : ApprenticeMgr.getConfigMap().values()) {
                if (ActivityHelper.activityInTime(apprenticeConfig.getActivityInfo())) {
                    return new ReturnData(GameErrorCode.E_APPRENTICE_CANNOT_BUY_IN_ACTIVITY_TIME);
                }
            }
        }

        //如果新版本财神密卷还没初始化 本地表情包商店不给买
        if (mallInfo.getShopType() == eShopType.WealthScrollEmojiMall.getValue()){
            if (!player.getModule(WealthScrollModule.class).isNewWealthScrollInTime()){
                return new ReturnData(GameErrorCode.E_MALL_NO_ACTIVITY_ABLE);
            }
        }


        //消耗
        Property consume = MallMgr.getPriceConsume(count, player.getModule(MallModule.class).getMallBuyCount(mallId), mallInfo);
        if (!player.getModule(CurrencyModule.class).currencyIsEnough(consume)) {
            int consumeGoods = 0;
            for (int key : consume.getGoods().keySet()) {
                consumeGoods = key;
                break;
            }
            if (consumeGoods == GameConfig.GAME_MONEY_INGOTS) {
                return new ReturnData(GameErrorCode.E_BAG_INGOTS_NO_ENOUGH);
            } else if (consumeGoods == GameConfig.BANQUET_INTEGRAL) {
                return new ReturnData(GameErrorCode.E_BANQUET_INTEGRAL_NO_ENOUGH);
            } else {
                return new ReturnData(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
            }
        }


        return new ReturnData(0, PropertyHelper.parsePropertyToString(consume));
    }

    public String buyGoods(int mallId, int count) {
        if(count <= 0){
            return "";
        }
        MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
        String reward = player.getModule(MallModule.class).buyGoods(mallInfo, count);
        if (mallInfo.getShopType() == eShopType.EstateWarMall.getValue()) { // 乔迁兑换商店
            player.notifyListener(eGamePlayerEventType.EstateWarMallBuyMallCount.getValue(), count);
        } else if (mallInfo.getShopType() == eShopType.UnionMall.getValue()) { // 商会兑换商店
            player.notifyListener(eGamePlayerEventType.UnionMallBuyTimes.getValue(), count);
            player.notifyListener(eGamePlayerEventType.UnionUnionMallBuyTimes.getValue(), new UnionActivityTaskArgs(UnionActivityTaskArgs.TYPE_ADD_VALUE, count, player.getUserInfo().getUnionUid()));
        }
        return reward;
    }

    /**
     * 购买物品
     */
    public String buyGoods(MallInfo mallInfo, int count) {
        //记录购买数量
        addMallBuyCount(mallInfo, count);
        if (mallInfo.getActivityId() > 0) {
            player.getModule(ActivityMallModule.class).addMallBuyCount(mallInfo, count);
        }
        //首充双倍
        Property resultProp = new Property();
        for (Entry<Integer, BigInteger> dataEntry : mallInfo.getRewardProp().getGoods().entrySet()) {
            resultProp.addProperty(dataEntry.getKey(), dataEntry.getValue().multiply(BigInteger.valueOf(count)));
        }

        if (RechargeMgr.isUseNewMultiple()) {
            player.getModule(RechargeGainModule.class).handleRechargeMultiple(mallInfo, resultProp, eRechargeGainIndex.GameFirstDouble.getValue());
        } else {
            if (player.getModule(RechargeGainModule.class).isFirstRechargeDouble(mallInfo, eRechargeGainIndex.GameFirstDouble.getValue())) {//翻倍
                for (Entry<Integer, BigInteger> dataEntry : resultProp.getGoods().entrySet()) {
                    dataEntry.setValue(dataEntry.getValue().multiply(BigInteger.valueOf(2)));
                }
                player.getModule(RechargeGainModule.class).changeRechargeGain(mallInfo.getMallId(), eRechargeGainIndex.GameFirstDouble.getValue());
            }
        }

        //物品进口袋
        player.getModule(CurrencyModule.class).addCurrency(resultProp, eLogMoneyType.Mall, eLogMoneyType.MallBuy);

        String priceStr = MallRechargeConfigMgr.getPriceStr(mallInfo);
        AutoLogMgr.add(new LogBuy(player.getUserId(), mallInfo.getMallId(), mallInfo.getReward(), count, priceStr,
                mallInfo.getShopType(), mallInfo.getActivityType(), player.getUserInfo().getVipExp(), mallInfo.getMallMarkId()));

        return PropertyHelper.parsePropertyToString(resultProp);
    }

    public void resetOneDay() {
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        List<UserMallBuyCount> syncList = new ArrayList<>();
        if (null != userMallBuyCountMap) {
            for (UserMallBuyCount userMallBuyCount : userMallBuyCountMap.values()) {
                MallInfo mallInfo = MallMgr.getMallInfoByMallId(userMallBuyCount.getMallId());
                if (null == mallInfo) {
                    continue;
                }
                boolean isReset = MallMgr.isMallBuyCountReset(zeroTime, userMallBuyCount, mallInfo);
                if (isReset) {
                    // 不等于0的才重新同步
                    if (userMallBuyCount.getCount() != 0) {
                        syncList.add(userMallBuyCount);
                    }
                    userMallBuyCount.setCount(0);
                    userMallBuyCount.setLastUpdateTime(zeroTime);

                }
            }
            syncMallBuyCount(syncList);
        }
    }

    //重置自定義商品的限购
    public void resetCustomMall(int shopType) {
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        List<UserMallBuyCount> syncList = new ArrayList<>();
        for (UserMallBuyCount userMallBuyCount : userMallBuyCountMap.values()) {
            MallInfo mallInfo = MallMgr.getMallInfoByMallId(userMallBuyCount.getMallId());
            if (null == mallInfo) {
                continue;
            }
            if (mallInfo.getShopType() == shopType) {
                if (mallInfo.getLimitBuyType() == eLimitBuyType.Custom.getValue()) {
                    userMallBuyCount.setCount(0);
                    userMallBuyCount.setLastUpdateTime(zeroTime);
                    syncList.add(userMallBuyCount);
                }
            }
        }
        syncMallBuyCount(syncList);
    }

    public void resetAssistantSkinMall(AssistantMallRandomGoods goods) {
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        List<UserMallBuyCount> syncList = new ArrayList<>();
        boolean needSync = false;
        for (UserMallBuyCount userMallBuyCount : userMallBuyCountMap.values()) {
            MallInfo mallInfo = AssistantCostumeMallActivityMgr.getMallInfoByMallId(userMallBuyCount.getMallId());
            if (null == mallInfo) {
                continue;
            }
            if (mallInfo.getShopType() == eShopType.AssistantSkinMall.getValue() && userMallBuyCount.getLastUpdateTime() < goods.getLastUpdateTime() / 1000) {
                if (mallInfo.getLimitBuyType() == eLimitBuyType.Custom.getValue()) {
                    userMallBuyCount.setCount(0);
                    userMallBuyCount.setLastUpdateTime(zeroTime);
                    syncList.add(userMallBuyCount);
                    needSync = true;
                }
            }
        }
        if (needSync) {
            syncMallBuyCount(syncList);
        }

    }


    public boolean isLimitBuy(int mallId, int count) {
        MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
        if (MallMgr.isLimitBuyGoods(player, mallInfo)) {
            return true;
        }
        if (-1 == mallInfo.getLimitBuyCount()) {
            return false;
        }
        int currentCount = 0;
        if (userMallBuyCountMap.containsKey(mallId)) {
            currentCount = userMallBuyCountMap.get(mallId).getCount();
        }
        boolean commonLimit = currentCount + count > mallInfo.getLimitBuyCount();
        if (commonLimit){   //如果已经被限购了 看看是否新的老玩家回归活动
            if (OldPlayerReturnMgr.getNowActivityType() == OldPlayerReturnActivityType.NEW_ACTIVITY.getValue()){
                OldPlayerReturnModule oldPlayerReturnModule = player.getModule(OldPlayerReturnModule.class);
                //查看一下是不是回归玩家
                if (oldPlayerReturnModule.checkUserIsReturn()){
                    //查看回归玩家是否有找回该商店的次数
                    OldPlayerReturnShopLimit oldPlayerReturnShopLimit = oldPlayerReturnModule.getOldPlayerReturnShopLimit(mallId);
                    if (oldPlayerReturnShopLimit == null){
                        return commonLimit;
                    }
                    return (currentCount + count) > (mallInfo.getLimitBuyCount() + oldPlayerReturnShopLimit.getTotalAddLimit() - oldPlayerReturnShopLimit.getHasBuyTimes());
                }
            }
        }
        return commonLimit;
    }


    public long getMallInfoLimitBuyCount(int mallId) {
        MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
        if (mallInfo != null) {
            for (Map.Entry<Integer, BigInteger> dataEntry : mallInfo.getRewardProp().getGoods().entrySet()) {
                if (GoodsMgr.isPatronsGoods(dataEntry.getKey())) {//门客不允许重复购买
                    return player.getModule(PatronsModule.class).getUserPatrons(dataEntry.getKey()) != null ? 0 : 1;
                }
                if (GoodsMgr.isBeautyGoods(dataEntry.getKey())) {//美女不允许重复购买
                    return player.getModule(BeautyModule.class).getUserBeauty(dataEntry.getKey()) != null ? 0 : 1;
                }
            }
            if (-1 == mallInfo.getLimitBuyCount()) {
                return GameConfig.MALL_BUY_MAX_COUNT;
            }
            return mallInfo.getLimitBuyCount();
        }
        return 0;
    }

    private void addMallBuyCount(MallInfo mallInfo, int count) {
        if (mallInfo.getPriceAdd() > 0 || -1 != mallInfo.getLimitBuyCount()) {// 如果是限购的 或者是有累加金额的才添加
            UserMallBuyCount mallBuyCount = userMallBuyCountMap.get(mallInfo.getMallId());
            if (null == mallBuyCount) {
                mallBuyCount = new UserMallBuyCount();
                mallBuyCount.setMallId(mallInfo.getMallId());
                mallBuyCount.setUserId(player.getUserId());
                mallBuyCount.setInsertOption();
                userMallBuyCountMap.put(mallBuyCount.getMallId(), mallBuyCount);
            }
            if (mallBuyCount.getCount()+count > mallInfo.getLimitBuyCount()){ //如果超过限购了,默认是回归玩家买的特殊次数
                OldPlayerReturnModule oldPlayerReturnModule = player.getModule(OldPlayerReturnModule.class);
                boolean reduceSuccess = oldPlayerReturnModule.reduceRecoverMallTime(mallInfo.getMallId(), mallBuyCount.getCount() + count - mallInfo.getLimitBuyCount());
                if (!reduceSuccess){
                    log.error("玩家{}在商店id{}中购买了{}次,超出限额!!!",getUserId(),mallInfo.getMallId(),count);
                }
                mallBuyCount.setCount(mallInfo.getLimitBuyCount());
                mallBuyCount.setLastUpdateTime(System.currentTimeMillis() / 1000);
                syncMallBuyCount(mallBuyCount);
                oldPlayerReturnModule.addMallLimitSync(oldPlayerReturnModule.getOldPlayerReturnShopLimit(mallInfo.getMallId()));
                return;
            }
            mallBuyCount.setCount(mallBuyCount.getCount() + count);
            mallBuyCount.setLastUpdateTime(System.currentTimeMillis() / 1000);
            syncMallBuyCount(mallBuyCount);
        }
    }

    public int getMallBuyCount(int mallId) {
        if (userMallBuyCountMap.containsKey(mallId)) {
            return userMallBuyCountMap.get(mallId).getCount();
        }
        return 0;
    }

    public void syncMallRebate(){
        Map<Integer, MallRebate> dataMap = MallRebateMgr.getMallRebateMap();
        MallProto.MallRebateListMsg.Builder syncMsg = MallPb.parseMallRebateListMsg(new ArrayList<>(dataMap.values()));
        player.sendPacket(Protocol.U_MALL_REBATE_SYNC, syncMsg);
    }
}
